import config from '../config/index';

export default class RewardedAds {
  constructor(adsId) {
    this.rewardedVideoAd = null; //广告实例
    this.adsId = adsId; //广告id
    this.isEnded = false; //是否看完激励性广告
    if(!config.showRewardAdsSaveHead)
    {
      this.isEnded = true;
    }
  }

  adInit(onCloseFnBack) {
    if(this.isEnded){
      return;
    }
    if (wx.createRewardedVideoAd) {
      this.rewardedVideoAd = wx.createRewardedVideoAd({
        adUnitId: this.adsId
      })
      this.rewardedVideoAd.onLoad(() => {
        console.log('onLoad event emit')
      })
      this.rewardedVideoAd.onError((err) => {
        console.log('onError event emit', err)
      })
      this.rewardedVideoAd.onClose((res) => {
        if(res && res.isEnded){
          this.isEnded = res.isEnded;
        }
        console.log('onClose event emit', res);
        onCloseFnBack && onCloseFnBack(res);
      })
    }
  }

  //显示广告
  showAd() {
    const self = this;
    self.rewardedVideoAd.show()
      .catch((e) => {
        console.log('111');
        console.log(e);
        this.isEnded = true; //无法加载广告，则默认通过
        self.rewardedVideoAd.load()
          .then(() => self.rewardedVideoAd.show())
          .catch(err => {
            wx.showModal({
              title: '提示',
              content: '广告加载失败，请重新点击保存头像',
              showCancel:false,
              confirmText:'我知道了'
            });
            console.log('激励视频 广告显示失败'. err);
            this.isEnded = true; //无法加载广告，则默认通过
          })
      })
  }

  resetAd(){
    this.isEnded = false; //会重新显示广告
    if(!config.showRewardAdsSaveHead)
    {
      this.isEnded = true;
    }
  }
}